<?php
/**
 * Created by PhpStorm.
 * User: raohouhai
 * Date: 2017/12/10
 * Time: 10:39
 */

namespace Xcx\Model;

use Think\Model;

class GoodsModel extends CommonModel
{
    /**
     * 获取商品详情
     * @return array
     */
    public function getGoodsList()
    {
        $maps['state'] = array('EQ','0');
        $list = $this->field('content',true)->where($maps)->select();
        if (is_array($list) && count($list) > 0) {
            return getUploadImgDir($list,array('goods'=>'img'));
        }
        return $list;
    }

    /**
     * 获取商品详情页信息
     * @param $gid
     * @return mixed
     */
    public function getGoodsDetails($gid)
    {
        //轮播
        $data['imgUrls'] = $this->getGoodsBanner($gid);
        $data['goods'] = $this->getGoodsInfo($gid);
        $data['specList'] = $this->getGoodsSpec($gid);
        return $data;
    }

    /**
     * 获取商品轮播图
     * @param $gid
     * @return array
     */
    public function getGoodsBanner($gid) {
        $maps['b.id'] = array('EQ',$gid);
        $data =  M('goods_banner')->alias('a')->field('a.*')->join('left join t_goods b on a.gid = b.id')->where($maps)->select();
        $sql = M()->getLastSql();
        if (is_array($data) && count($data) > 0) {
            return getUploadImgDir($data,array('goods_banner'=>'img'));
        }
        return array();
    }

    /**
     * 获取商品信息
     * @param $gid
     * @return array
     */
    public function getGoodsInfo($gid) {
        $maps['id'] = array('EQ',$gid);
        $data = $this->where($maps)->find();
        if (is_array($data) && count($data) > 0) {
            $specList = $this->getGoodsSpec($gid);
            $data['price'] = $specList[0]['price'];
            $data['content'] = $this->dealContentImgs($data['content']);
            $data['img'] = getUploadImgDir($data['img'],'goods');
            return $data;
        }
        return array();
    }

    /**
     * 替换编辑器里面图片路径
     * @param $content
     * @return mixed
     */
    private function dealContentImgs($content)
    {
        $search = "/Public/upload/ueditor/";
        $replace = HTTP_TYPE.$_SERVER['HTTP_HOST']."/Public/upload/ueditor/";
        return str_replace($search,$replace,$content);
    }

    /**
     * 获取商品规格数组
     * @param $gid
     * @return array
     */
    public function getGoodsSpec($gid) {
        $maps['b.id'] = array('EQ',$gid);
        $maps['a.state'] = array('EQ','0');
        $data =  M('goods_spec')->alias('a')
            ->field('a.*')
            ->join('left join t_goods b on a.gid = b.id')
            ->order(array('a.price'=>'asc'))
            ->where($maps)
            ->select();
        if (is_array($data) && count($data) > 0) return $data;
        return array();
    }
}
